package com.baoxin.consumer.controller;



import com.baoxin.consumer.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("consumer")
@DefaultProperties(defaultFallback = "defaultFallback")
public class UserController {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient ;

    @GetMapping("{id}")
    // @HystrixCommand(fallbackMethod = "queryByIdForback") 当只有一个方法的时候，可以这样写， 当有多个方法的时候，就需要用第二种写法
    @HystrixCommand
    public String  queryById(@PathVariable("id") Long id ){

        if(id == 1){
            throw  new RuntimeException("服务器繁忙，请稍后重试！");
        }

        String url = "http://user-service/user/"+id ;

        String user = restTemplate.getForObject(url, String.class);

        return  user ;
    }

    /**
     *
     *  熔断处理
     *
     * @param id
     * @return
     */
    public String queryByIdForback(@PathVariable("id") Long id ){

        log.info("查询用户信息失败。 id:{}",id);

        return "对不起，网络太拥挤了！";
    }

    /**
     *  默认的服务熔断方法
     *
     * @return
     */
    public String defaultFallback( ){

        log.info("默认提示：查询用户信息失");

        return "默认提示： 对不起，网络太拥挤了！";
    }



    public User queryByIdOne(Long id ){

        String url = "http://user-service/user/"+id ;

        User user = restTemplate.getForObject(url, User.class);

        return  user ;
    }

    public User getUserService(@PathVariable("id") Long id) {
        // 获取 eureka 中注册的user-service 的实例
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");

        ServiceInstance serviceInstance = instances.get(0);

        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/" +id ;

        log.info("url= " + url);

        return restTemplate.getForObject(url, User.class);
    }

    private User getUser(@PathVariable("id") Long id) {
        String url = "http://127.0.0.1:9091/user/" + id ;

        log.info("请求的url地址为："+ url);

        return restTemplate.getForObject(url, User.class);
    }

}
